<template>
  <el-card class="account-container">
    <el-form :model="configForm" :rules="rules" ref="configRef" label-width="120px" label-position="right">
      <el-form-item label="名称：" prop="title">
        <el-input style="width: 200px" v-model="configForm.title"></el-input>
      </el-form-item>
      <el-form-item label="作者：" prop="author">
        <el-input style="width: 200px" v-model="configForm.author"></el-input>
      </el-form-item>
      <el-form-item label="生成包路径" prop="packageName">
        <el-input style="width: 200px" v-model="configForm.packageName"></el-input>
      </el-form-item>
      <el-form-item label="去除表前缀：" prop="autoRemovePre">
        <el-switch v-model="configForm.autoRemovePre" active-color="#13ce66" active-value="1"></el-switch>

      </el-form-item>
      <el-form-item label="表前缀" prop="tablePrefix">
        <el-input style="width: 200px" v-model="configForm.tablePrefix"></el-input>
      </el-form-item>

      <el-form-item label="保存路径" prop="genPath">
        <el-input style="width: 200px" @click="openDialog"  v-model="configForm.genPath"></el-input>
        <el-button @click="openDialog">...</el-button>
      </el-form-item>

        <el-form-item label="模版ID" prop="templateId">
                <el-select @change="handleOption" v-model="configForm.templateId" size="small">
                    <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>

      <el-form-item>
        <el-button @click="submitForm">确认修改</el-button>
         <el-button @click="genCode">生成代码</el-button>
      </el-form-item>
    </el-form>
  </el-card>

</template>

<script lang="ts">
  import {
    onMounted,
    reactive,
    ref,
    toRefs
  } from 'vue'
  import * as db_context from '@/models/db_context'
  import commonAction from '@/utils/common'
  const fs = window.require('fs')
  
  import {
    ElMessage,
    ElTable
  } from 'element-plus'
  const {
    ipcRenderer,
    remote
  } = window.require('electron');
  export default {
    name: 'Home',

    setup() {

      const configRef = ref < any > (null) // 修改名称 ref

      const state = reactive({
         options: [],
        configForm: {
          title: '',
          author: '',
          packageName: '',
          autoRemovePre: '',
          tablePrefix: '',
          genPath: '',
          templateId: 0

        },
        // 验证配置对象
        rules: {
          title: [{
            required: 'true',
            message: '标题不能为空',
            trigger: ['change']
          }],
          author: [{
            required: 'true',
            message: '作者不能为空',
            trigger: ['change']
          }],
          packageName: [{
            required: 'true',
            message: '包名不能为空',
            trigger: ['change']
          }],
          packaggenPatheName: [{
            required: 'true',
            message: '保存路径不能为空',
            trigger: ['change']
          }],
          templateId: [{
            required: 'true',
            message: '模版不能为空',
            trigger: ['change']
          }]
        },
      })

      onMounted(() => {
        getConfig()
      })

      // 获取数据列表
      const getConfig = async () => {


       const resultTem:any= await db_context.Template.getList<db_context.Template>();
         state.options=resultTem;

         console.log(resultTem);


        const results: any = await db_context.Project.getById < db_context.Project > (1);
        state.configForm = results;
         console.log(results);
      }


      function openDialog() {
        console.log('dialog');
        ipcRenderer.send('open-directory-dialog');

        ipcRenderer.on('selected-directory', (event, path: Array < string > ) => {
          console.log(path[0])
          if (path) {
            state.configForm.genPath = path[0];
            console.log(path);
          } else {
            console.log('路径错误');
          }
        });

      }


      // 提交修改
      const submitForm = () => {


        if (!configRef.value) return;
        configRef.value.validate(async (valid: boolean) => {
          if (valid) {
            const formvalue: any = state.configForm;
            await db_context.Project.updateItemById < db_context.Project > (formvalue, 1);
            await commonAction.resetTables("");
            ElMessage.success("更新成功")
         
          }
        });

      }


     

      const genCode = async () => {
        //获取保存路径
        if(state.configForm.genPath==""){
           ElMessage.error("保存路径不能为空")
           return;
        }
        

        //遍历文件保存
         const preView=await commonAction.preViewCode("");
         for (let k in preView) {
               let codes = preView[k];
               codes.forEach((element:any) => {
                 // console.log(element);
                 // var data=fs.readFileSync('README.md', 'utf-8');..
                  let path:any=state.configForm.genPath;
                  if(element.path!=""){
                    path=path+"\\"+element.path+"\\";
                  }
                  const filepath=path+element.title;
                  console.log('检测path:'+path)
                  if(!fs.existsSync(path)){
                     console.log('创建path:'+path)
                    fs.mkdirSync(path,{ recursive: true });
                  }
                 //  path=path+element.title;
                  // console.log('保存路径'+path)
                   //console.log('文件路径'+filepath)

                 fs.exists(filepath,(exist:boolean)=>{
    if(exist){
        //console.log('已经存在');
         ElMessage.error(filepath+'已经存在')
    }else{
       
        fs.writeFile(filepath,element.content,(error:boolean)=>{
            if(error){
                
                  ElMessage.error(filepath+'写入失败')
                return;
            }else{
                ElMessage.success(filepath+'成功')
               // console.log('成功');
            }
            
        });
    }
})
                 //save..............................................
                 
               });
               
           }
         
      }

  


      return {
        ...toRefs(state),
        configRef,
        submitForm,
        openDialog,
        genCode

      }


    }
  }
</script>

<style scoped>
  .aaa {
    min-height: 100%;
  }
</style>